package com.bit.cfdi.web.dao.impl;

import java.util.List;

import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import com.bit.cfdi.web.dao.PersonaDAO;
import com.bit.cfdi.web.domain.Persona;

@Repository
public class PersonaDAOImpl extends HibernateDaoSupport implements PersonaDAO {

	@Autowired
	public void init(final SessionFactory sessionFactory) throws DataAccessException {
		setSessionFactory(sessionFactory);
	}
	
	@Transactional
	@Override
	public void save(final Persona persona) throws DataAccessException {
		getHibernateTemplate().saveOrUpdate(persona);
	}

	@Transactional
	@SuppressWarnings("unchecked")
	@Override
	public Persona getById(final Long id) throws DataAccessException {
		List<Persona> personas = getHibernateTemplate().find(
				" from Persona as p" +
				" where p.idPersona=?", id);
		return personas.size()>0?personas.get(0):null;
	}

	@Transactional
	@SuppressWarnings("unchecked")
	@Override
	public List<Persona> getAll() throws DataAccessException {
		List<Persona> personas = getHibernateTemplate().find(
				" from Persona as p");
		return personas;
	}

	@Transactional
	@SuppressWarnings("unchecked")
	@Override
	public Persona getByRFCAndName(final String rfc, final String name) throws DataAccessException {
		String query = "select per from Persona as per, " +
				"Direccion as dir, DatosFiscales as dfiscal " +
				"where per.direccion.idDireccion = dir.idDireccion " +
				"and dir.idDireccion = dfiscal.direccion.idDireccion " +
				"and dfiscal.rfc = ? and per.nombre = ?";
		List<Persona> persona = getHibernateTemplate().find(query, rfc, name);
		return !persona.isEmpty() ? persona.get(0) : null;
	}

}
